var mapvLayer;
/**
 * 地图筛选
 */ 
var bisScreening = {
    id: "bigScreeningDiv"   //Div id
};

//ztree树形展示
var setting = {
	view: {
		showIcon: false,
		selectedMulti: false
	},
	data: {
		simpleData: {
			enable: true
		}
	},
	callback: {
		beforeClick: beforeClick,
		onClick: onClick
	}
};

/**
 * 全局变量
 */

var radius;//半径
var point;//点对象
var map;//地图对象

function showLog(str) {
	//console.log(str);
}
function beforeClick(treeId, treeNode, clickFlag) {
	showLog(treeNode.level);
	if(treeNode.level==0){
		return false
	}else{
		return true;
	}
}
function getTime() {
	var now= new Date(),
	h=now.getHours(),
	m=now.getMinutes(),
	s=now.getSeconds();
	return (h+":"+m+":"+s);
}

function addflyLineChar(data,city,areaId,subAreaId){
	//获取最新时间
	var maxHour;
	var maxMinutes;
	var maxDay;
	var maxsubHour;
	var maxsubDay;
	var maxsubMinutes;
	var dateString;
	var maxTimeAjax = new $ax(Feng.ctxPath + "/bigSrceen/maxTime?areaId="+areaId+"&subAreaId="+subAreaId,
	    function (data) {
			data = eval("("+data+")");
			maxsubHour = data.submaxHourTime;
			maxsubDay = data.submaxDayTime;
			maxsubMinutes = data.subminutesTime;
			maxHour = data.hourTime;
			maxDay = data.dayTime;
			maxMinutes = data.minutesTime;
			dateString = data.dateString;
			var content = document.getElementById("selectArea").innerHTML;
			document.getElementById('time').innerHTML="逍遥-"+content+" "+dateString;
			$.get('/static/json/china.json', function(geojson) {
		        var geojsonOptions = {
		            gradient: {
		                0: 'rgba(55, 50, 250, 0.4)',
		                1: 'rgba(55, 50, 250, 1)'
		            },
		            max: 354551,
		            draw: 'intensity'
		        }
		        var geojsonDataSet = mapv.geojson.getDataSet(geojson);
		        var to = city;
		        var outsideUserAjax = new $ax(Feng.ctxPath + "/bigSrceen/outsideUser?areaId="+areaId+"&subAreaId="+subAreaId+"&maxHour="+maxHour+"&maxsubHour="+maxsubHour,
		        		function (data) {
		    		var data = eval("("+data+")");
		    		var nameArray = [];
		    		var valueArray = [];
		    		for (var i = 0; i < data.length; i++) {
		    			//nameArray.push(data[i].name);
		    			var str = {from:data[i].name, count:data[i].count, to:to};
		    			valueArray.push(str);
		    		}
		    		var qianxi = new mapv.DataSet(valueArray);
		    		var qianxiData = qianxi.get();
			        var lineData = [];
			        var pointData = [];
			        var textData = [];
			        var timeData = [];
			        var citys = {}
			        for (var i = 0; i < qianxiData.length; i++) {
			            var fromCenter = mapv.utilCityCenter.getCenterByCityName(qianxiData[i].from);
			            var toCenter = mapv.utilCityCenter.getCenterByCityName(qianxiData[i].to);
			            if (!fromCenter || !toCenter) {
			                continue;
			            }
			            citys[qianxiData[i].from] = qianxiData[i].count;
			            citys[qianxiData[i].to] = 100;
			            pointData.push(
			            {
			                geometry: {
			                    type: 'Point',
			                    coordinates: [fromCenter.lng, fromCenter.lat]
			                }
			            }
			            );
			            pointData.push(
			            {
			                geometry: {
			                    type: 'Point',
			                    coordinates: [toCenter.lng, toCenter.lat]
			                }
			            }
			            );
			            textData.push(
			            {
			                geometry: {
			                    type: 'Point',
			                    coordinates: [fromCenter.lng, fromCenter.lat]
			                },
			                text: qianxiData[i].from
			            }
			            );
			            textData.push(
			            {
			                geometry: {
			                    type: 'Point',
			                    coordinates: [toCenter.lng, toCenter.lat]
			                },
			                text: qianxiData[i].to
			            }
			            );
			            var curve = mapv.utilCurve.getPoints([fromCenter, toCenter]);
			            for (j = 0; j < curve.length; j++) {
			                timeData.push({
			                    geometry: {
			                        type: 'Point',
			                        coordinates: curve[j]
			                    },
			                    count: 1,
			                    time: j
			                });
			            }
			            lineData.push({
			                geometry: {
			                    type: 'LineString',
			                    coordinates: curve
			                    //coordinates: [[fromCenter.lng, fromCenter.lat], [toCenter.lng, toCenter.lat]]
			                },
			                count: 30 * Math.random()
			            });
			        }
			        var data = geojsonDataSet.get({
			            filter: function (item) {
			                if (!citys[item.name]) {
			                    return false;
			                }
			                item.count = citys[item.name];
			                return true;
			            }
			        });
			        geojsonDataSet = new mapv.DataSet(data);
			        var mapvLayer = new mapv.baiduMapLayer(map, geojsonDataSet, geojsonOptions);
			        var textDataSet = new mapv.DataSet(textData);
			        var textOptions = {
			            draw: 'text',
			            font: '14px Arial',
			            fillStyle: 'white',
			            shadowColor: 'yellow',
			            shadowBlue: 10,
			            zIndex: 11,
			            shadowBlur: 10
			        }
			        var textMapvLayer = new mapv.baiduMapLayer(map, textDataSet, textOptions);
			        var lineDataSet = new mapv.DataSet(lineData);
			        var lineOptions = {
			            strokeStyle: 'rgba(255, 250, 50, 0.8)',
			            shadowColor: 'rgba(255, 250, 50, 1)',
			            shadowBlur: 20,
			            lineWidth: 2,
			            zIndex: 100,
			            draw: 'simple'
			        }
			        var lineLayer = new mapv.baiduMapLayer(map, lineDataSet, lineOptions);
			        var pointOptions = {
			            fillStyle: 'rgba(254,175,3,0.7)',
			            shadowColor: 'rgba(55, 50, 250, 0.5)',
			            shadowBlur: 10,
			            size: 5,
			            zIndex: 10,
			            draw: 'simple'
			        }
			        var pointDataSet = new mapv.DataSet(pointData);
			        var pointLayer = new mapv.baiduMapLayer(map, pointDataSet, pointOptions);
			        var timeDataSet = new mapv.DataSet(timeData);
			        //console.log(timeData);
			        var timeOptions = {
			            fillStyle: 'rgba(255, 250, 250, 0.5)',
			            zIndex: 200,
			            size: 2.5,
			            animation: {
			                type: 'time',
			                stepsRange: {
			                    start: 0,
			                    end: 50
			                },
			                trails: 10,
			                duration: 2,
			            },
			            draw: 'simple'
			        }
			        var timeMapvLayer = new mapv.baiduMapLayer(map, timeDataSet, timeOptions);
		        },
		        function (data) {
		            alert("网络繁忙，请稍后再试！");

		        });
		        outsideUserAjax.start();
		    });
	    },
	    function (data) {
	        alert("网络繁忙，请稍后再试！");
	    });
	maxTimeAjax.start();
}

function addArea(data){
	//count 权重
	for(i=0;i<data.length;i++){
		var heatmapArray = [];
		if(data[i].lon.indexOf(';') != -1){
			var lons = data[i].lon.split(';');
			var lats = data[i].lat.split(';');
			var counts = data[i].popCount.split(';');
			for(j=0;j<lons.length;j++){
				var item={
					lng: Number(lons[j]),
					lat: Number(lats[j]),
					count: Number(counts[j])
					};
				heatmapArray.push(item);
			}
		}else{
			var item={
				lng: Number(data[i].lon),
				lat: Number(data[i].lat),
				count: Number(data[i].popCount)
	        	};
				heatmapArray.push(item);
		}
		}
		//setInterval(showHeatMap,5000);//每隔5秒请求服务器获取最新数据
	
	//参数说明如下:
	/* visible 热力图是否显示,默认为true
     * opacity 热力的透明度,1-100
     * radius 势力图的每个点的半径大小   
     * gradient  {JSON} 热力图的渐变区间 . gradient如下所示
     *	{
			.2:'rgb(0, 255, 255)',
			.5:'rgb(0, 110, 255)',
			.8:'rgb(100, 0, 255)'
		}
		其中 key 表示插值的位置, 0~1. 
		    value 为颜色值. 
     */
	heatmapOverlay = new BMapLib.HeatmapOverlay({"radius":50});
	map.addOverlay(heatmapOverlay);
	heatmapOverlay.setDataSet({data:heatmapArray,max:1000});
}

setInterval(function () {
	map.clearOverlays();
	findName();
},60*1000);

//是否显示热力图
function openHeatmap(){
    heatmapOverlay.show();
}
function closeHeatmap(){
    heatmapOverlay.hide();
}

function setGradient(){
 	/*格式如下所示:
	{
  		0:'rgb(102, 255, 0)',
 	 	.5:'rgb(255, 170, 0)',
	  	1:'rgb(255, 0, 0)'
	}*/
 	var gradient = {};
 	var colors = document.querySelectorAll("input[type='color']");
 	colors = [].slice.call(colors,0);
 	colors.forEach(function(ele){
		gradient[ele.getAttribute("data-key")] = ele.value; 
 	});
    heatmapOverlay.setOptions({"gradient":gradient});
}

function thiessenPolygonColorByIndex(data) {
	var popCount = data.popCount;
	var warningValue = data.warningValue;
	var saturationValue = data.saturationValue;
	var severeValue = data.severeValue;
	var index;
	if(popCount>0 && popCount<=warningValue){
		index = 0;
	}else if(popCount>warningValue && popCount<=saturationValue){
		index = 1;
	}else if(popCount>saturationValue && popCount<=severeValue){
		index = 2;
	}else if(popCount>severeValue){
		index = 3;
	}
    var colors = ['#46B035', '#9BC702', '#FFAE00', '#FD3023'];
    //var colors = ['#46B035', '#9BC702', '#FFAE00', '#FF7200', '#FD3023']
    return colors[index]
}

var city;
var lon;
var lat;
var lonLat;
var areaId;
var subAreaId;
var ztree;
function onClick(event, treeId, treeNode, clickFlag) {
	showLog("[ "+getTime()+" onClick ]&nbsp;&nbsp;clickFlag = " + clickFlag + " (" + (clickFlag===1 ? "普通选中": (clickFlag===0 ? "<b>取消选中</b>" : "<b>追加选中</b>")) + ")");
	showLog(treeNode);
	var id = treeNode.id;
	var level = treeNode.level;
	$("#selectArea").html(treeNode.name);
	if(level==1){
		$("#areaId").val(id);
		$("#subAreaId").val("");
		findName();
		areaReset();
	}else if(level==2){
		var parentNode=treeNode.getParentNode();
		$("#areaId").val(parentNode.id);
		$("#subAreaId").val(id);
		findName();
		areaReset();
	}
	
}

function getFirstAreaId(){
	var treeObj =  $.fn.zTree.getZTreeObj("areaTree");
	var nodes = treeObj.getNodes();
	for(i=0;i<nodes.length;i++){
		if(nodes[i].children!=undefined ){
			var childnodes = nodes[i].children;
			for(j=0;j<childnodes.length;i++){
				if(childnodes[j].id!=undefined ){
					return childnodes[j];
				}else{
					return null;
				}
			}
		}
	}
}

function findName(){
	areaId =$("#areaId").val();
	if(areaId==null||areaId==''){
		var area=getFirstAreaId();
		if(area!=null){
			areaId=area.id;
			$("#selectArea").html(area.name);
		};
	}
	subAreaId =$("#subAreaId").val();
	var findNameAjax = new $ax(Feng.ctxPath + "/bigSrceen/findName?areaId="+areaId+"&subAreaId="+subAreaId, function (data) {
		//alert(JSON.stringify(data)+'-----');
		//这里做了转义处理
		data = JSON.parse(data);
		city=data[0].cityName;
		lonCenter=data[0].lonCenter;
		latCenter=data[0].latCenter;
		lonLat=data.lonLat;
		map = new BMap.Map("allmap",{enableMapClick:false}); // 创建Map实例
		//map.setMapStyle({style:'midnight'});
	    map.setCurrentCity(city);  // 设置地图显示的城市 此项是必须设置的
	    map.centerAndZoom(new BMap.Point(lonCenter, latCenter), 5);
	    map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
	    //map.addOverlay(new BMap.Marker(new BMap.Point(lonCenter, latCenter)));
	    //addArea(data);
	    map.setMapStyle({
            styleJson: [{
                "featureType": "water",
                "elementType": "all",
                "stylers": {
                    "color": "#031628"
                }
            }, {
                "featureType": "land",
                "elementType": "geometry",
                "stylers": {
                    "color": "#000102"
                }
            }, {
                "featureType": "highway",
                "elementType": "geometry.fill",
                "stylers": {
                    "color": "#000000"
                }
            }, {
                "featureType": "highway",
                "elementType": "geometry.stroke",
                "stylers": {
                    "color": "#147a92"
                }
            }, {
                "featureType": "arterial",
                "elementType": "geometry.fill",
                "stylers": {
                    "color": "#000000"
                }
            }, {
                "featureType": "arterial",
                "elementType": "geometry.stroke",
                "stylers": {
                    "color": "#0b3d51"
                }
            }, {
                "featureType": "local",
                "elementType": "geometry",
                "stylers": {
                    "color": "#000000"
                }
            }, {
                "featureType": "railway",
                "elementType": "geometry.fill",
                "stylers": {
                    "color": "#000000"
                }
            }, {
                "featureType": "railway",
                "elementType": "geometry.stroke",
                "stylers": {
                    "color": "#08304b"
                }
            }, {
                "featureType": "subway",
                "elementType": "geometry",
                "stylers": {
                    "lightness": -70
                }
            }, {
                "featureType": "building",
                "elementType": "geometry.fill",
                "stylers": {
                    "color": "#000000"
                }
            }, {
                "featureType": "all",
                "elementType": "labels.text.fill",
                "stylers": {
                    "color": "#857f7f"
                }
            }, {
                "featureType": "all",
                "elementType": "labels.text.stroke",
                "stylers": {
                    "color": "#000000"
                }
            }, {
                "featureType": "building",
                "elementType": "geometry",
                "stylers": {
                    "color": "#022338"
                }
            }, {
                "featureType": "green",
                "elementType": "geometry",
                "stylers": {
                    "color": "#062032"
                }
            }, {
                "featureType": "boundary",
                "elementType": "all",
                "stylers": {
                    "color": "#465b6c"
                }
            }, {
                "featureType": "manmade",
                "elementType": "all",
                "stylers": {
                    "color": "#022338"
                }
            }, {
                "featureType": "label",
                "elementType": "all",
                "stylers": {
                    "color": "#022338",
                    "visibility": "off"
                }
            }]
        });
	    addflyLineChar(data,city,areaId,subAreaId);
	}, function (data) {
		map = new BMap.Map("allmap"); // 创建Map实例
		map.setCurrentCity("湖北省");  // 设置地图显示的城市 此项是必须设置的
		map.centerAndZoom("湖北省", 9);
		map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
	});
	findNameAjax.start();
}

$(function () {
	ztree = new $ZTree("areaTree", "/screening/tree");
	ztree.setSettings(setting);
    ztree.init();
	findName();
	//加载ztre
	$(".dropdown-menu").on('click', function (e) {
        e.stopPropagation();
    });
	var windowWidth = $(window).width();
    var chartWidth = $(".echarts").width(windowWidth*0.88);
    $(window).resize( function(){
        var windowWidth = $(window).width();
        var chartWidth = $(".echarts").width(windowWidth*0.88);
    });
    $(window).resize( function(){
        var windowWidth = $(window).width();
    });
});